package cn.cdutetc.library.service;

import cn.cdutetc.library.entity.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 定时备份服务
 */
@Slf4j
@Service
public class ScheduledBackupService {

    @Autowired
    private BackupService backupService;

    /**
     * 每日自动备份
     * 每天凌晨2点执行
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void dailyBackup() {
        try {
            log.info("开始执行每日自动备份任务");
            
            // 生成备份名称
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String backupName = "每日备份_" + dateStr;
            String description = "系统每日自动备份，备份时间: " + LocalDateTime.now();
            
            // 创建系统用户用于记录
            User systemUser = new User();
            systemUser.setUserId(0);
            systemUser.setRealName("系统自动任务");
            
            // 执行备份
            backupService.createBackup(backupName, description, systemUser);
            
            log.info("每日自动备份任务完成");
        } catch (Exception e) {
            log.error("每日自动备份任务失败", e);
        }
    }

    /**
     * 每周自动备份
     * 每周一凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * MON")
    public void weeklyBackup() {
        try {
            log.info("开始执行每周自动备份任务");
            
            // 生成备份名称
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String backupName = "每周备份_" + dateStr;
            String description = "系统每周自动备份，备份时间: " + LocalDateTime.now();
            
            // 创建系统用户用于记录
            User systemUser = new User();
            systemUser.setUserId(0);
            systemUser.setRealName("系统自动任务");
            
            // 执行备份
            backupService.createBackup(backupName, description, systemUser);
            
            log.info("每周自动备份任务完成");
        } catch (Exception e) {
            log.error("每周自动备份任务失败", e);
        }
    }


    /**
     * 手动触发备份（用于测试）
     */
    public void manualBackup() {
        try {
            log.info("开始执行手动备份任务");
            
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String backupName = "手动备份_" + dateStr;
            String description = "手动触发的备份，备份时间: " + LocalDateTime.now();
            
            // 创建系统用户用于记录
            User systemUser = new User();
            systemUser.setUserId(0);
            systemUser.setRealName("系统管理员");
            
            // 执行备份
            backupService.createBackup(backupName, description, systemUser);
            
            log.info("手动备份任务完成");
        } catch (Exception e) {
            log.error("手动备份任务失败", e);
        }
    }
}
